#!/data/Software/mydan/perl/bin/perl -I/data/Software/mydan/Connector/lib -I/data/Software/mydan/Connector/private/lib
use strict;
use warnings;
use JSON;
use YAML::XS;
use LWP::UserAgent;
my %app;
my ( $ssousername, %env );
BEGIN{
    for my $file ( glob "/data/Software/mydan/*/conf/appname" )
    {
        my $name = `cat $file`;
        chomp $name;
        $file =~ s/appname/appkey/;
        my $key = `cat $file`;
        chomp $key;
        $app{$name} = $key eq 'c3random' && $ENV{OPEN_C3_RANDOM} ? $ENV{OPEN_C3_RANDOM} : $key;
    }
    use Configini;
    $ssousername = Configini::get( 'ssousername' );
    %env = Configini::env( 'ssousernameenv' );
    die "ssousername undef on config.ini" unless $ssousername;
};

$| ++;

=head1 SYNOPSIS

#第一种
    cookie => 'MTUxNTAzMzg1NnxEdi1CQkFFQ180SUFBUXdCRUFBQU5mLUNBQUVGZEc5clpXNEdjM1J5YVc1bkRDSUFJREk0T1Rsa1l6aG1ZMk5tWWpRMk16TmtaV1kzTlRSbE1XWmtNVFpsTW1JeHyVJcLDk8iEGWlwsv8le0WzgNxhZ6JIYRFMOYzE8fKecA==',

#第二种
    appkey =>
    appname => 

=cut

return sub
{
    my %param = @_;
    return 'debug@api' if $ENV{MYDan_DEBUG};
    if( $param{appkey} && $param{appname} )
    {
         return undef unless $app{$param{appname}} && $app{$param{appname}} eq $param{appkey};
         return wantarray ? ( "$param{appname}\@app", '@app' ) : "$param{appname}\@app";
    }
    else
    {
        my $ua = LWP::UserAgent->new;
        $ua->default_header( %env ) if %env;
        my $res = $ua->get( "$ssousername$param{cookie}" );
        if($res->is_success)
        {
            my $v = eval{decode_json $res->decoded_content};
            return undef unless $v->{stat};
            my @return = ( ref $v->{data} eq 'HASH' && $v->{data}{user} && $v->{data}{company} )
                ? ( $v->{data}{user}, $v->{data}{company}, $v->{data}{admin}, $v->{data}{showconnector} )
                : ref $v->{data} eq 'HASH' ? () : ( $v->{data}, $v->{data} =~ /(@.+)$/ ? $1 : 'default' );

            return wantarray ? @return : $return[0];
        }
        return undef;
    }
}
